/**
 * @file: 字典管理
 * @author: Lengxx
 * @date: 2024-06-26
 */
<template>
  <PageWrapper title="字典管理" >
    <TableFilterForm :formState="filterState" @search="onSearch" >
      <FormItem label="字段类型" >
        <Input placeholder="请输入字段类型" v-model:value="filterState.type" />
      </FormItem>
    </TableFilterForm>
    <BasicTable @register="tableRegister">
      <template #toolbar>
        <Button type="primary" @click="onAddDictionary">新增</Button>
      </template>
      <template #operate="{ record }">
        <Button type="link" size="small" @click="onRowAction(TableRowActionEnum.Edit, record)">编辑</Button>
        <Button type="link" danger size="small" @click="onRowAction(TableRowActionEnum.Delete, record)">删除</Button>
      </template>
    </BasicTable>

    <AddDictionaryModal @register="addModalRegister" @submit="onAddModalSubmit" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import * as api from '@/api/dictionary'
import { useRequest } from '@vben/hooks'
import { tableColumns } from './settings';
import { useModal } from '@/components/Modal'
import { PageWrapper } from '@/components/Page'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicTable, useTable, TableFilterForm } from '@/components/Table'
import { Button, FormItem, Input } from 'ant-design-vue'
import AddDictionaryModal from './components/AddDictionaryModal.vue'
import { ModalTypeEnum, TableRowActionEnum } from '@/enums/appEnum';
import { IDictionaryResp } from '@/api/dictionary/model';

const { loading, data, runAsync: reflesh } = useRequest(api.getDictList);

const { createMessage, createConfirm } = useMessage()

const [addModalRegister, { openModal: openAddModal, closeModal: closeAddModal }] = useModal()

const [tableRegister] = useTable({
  loading,
  columns: tableColumns,
  dataSource: data
})

const filterState = reactive({
  type: ''
})

function onAddDictionary() {
  openAddModal(true, { modalType: ModalTypeEnum.Add });
}

function onAddModalSubmit() {
  closeAddModal();
  createMessage.success('操作成功!');
  reflesh();
}

/** 表格行操作 */
function onRowAction(actionType: TableRowActionEnum, record: IDictionaryResp) {
  switch(actionType) {
    case TableRowActionEnum.Edit:
      openAddModal(true, { ...record, modalType: ModalTypeEnum.Edit })
      break
    case TableRowActionEnum.Delete:
      createConfirm({
        title: '提示',
        content: '是否删除该选项？',
        iconType: 'info',
        onOk: async () => {
          await api.deleteDictionary(record.id);
          createMessage.success('删除成功!');
          reflesh();
        }
      })
      break
    default:
      break
  }
}

function onSearch() {
  const { type } = filterState;
  reflesh(type);
}

</script>
